<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const data = ref([])
const loading = ref(false)
const topicFilter = ref('')
const typeFilter = ref('')

const fetchLogs = async () => {
  try {
    loading.value = true
    // 获取所有类型的日志（包括接收到的消息）
    const params = { 
      limit: 200
      // 不限制类型，获取所有日志
    }
    
    // 添加主题筛选参数
    if (topicFilter.value.trim()) {
      params.topic = topicFilter.value.trim()
    }
    
    // 添加类型筛选参数
    if (typeFilter.value) {
      params.type = typeFilter.value
    }
    
    const { data: resp } = await axios.get('/api/logs', { params })
    if (resp?.success) data.value = resp.logs
  } catch (e) { ElMessage.error('获取日志失败') }
  finally { loading.value = false }
}

const clearLogs = async () => {
  try {
    // 发送必需的确认参数
    const response = await axios.delete('/api/logs', {
      data: {
        confirm: true,
        password: 'DELETE_ALL_LOGS_CONFIRM'
      }
    })
    // 使用后端返回的消息或默认消息
    ElMessage.success(response?.data?.message || '已清空')
    // 刷新日志列表以显示空状态
    fetchLogs()
  } catch (e) { 
    ElMessage.error('清空失败: ' + (e?.response?.data?.message || e.message))
  }
}

// 格式化时间为中文格式，兼容已是中文格式的字符串
const formatChineseTime = (timestamp) => {
  if (!timestamp) return ''
  // 已是中文格式，直接返回
  if (typeof timestamp === 'string' && /\d{4}年\d{2}月\d{2}日/.test(timestamp)) return timestamp
  const date = new Date(timestamp)
  if (isNaN(date.getTime())) return typeof timestamp === 'string' ? timestamp : ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
}

// 清空筛选
const clearFilters = () => {
  topicFilter.value = ''
  typeFilter.value = ''
  fetchLogs()
}

// 获取所有主题列表（用于筛选选项）
const allTopics = computed(() => {
  const topics = new Set()
  data.value.forEach(log => {
    if (log.topic) {
      topics.add(log.topic)
    }
  })
  return Array.from(topics).sort()
})

onMounted(fetchLogs)
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span>MQTT日志查看器</span>
        <div>
          <el-button size="small" @click="fetchLogs" :loading="loading">刷新</el-button>
          <el-button size="small" type="danger" @click="clearLogs">清空</el-button>
        </div>
      </div>
    </template>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>主题筛选：</label>
          <el-select 
            v-model="topicFilter" 
            placeholder="选择主题" 
            clearable 
            filterable
            style="width: 200px;"
            @change="fetchLogs"
          >
            <el-option
              v-for="topic in allTopics"
              :key="topic"
              :label="topic"
              :value="topic"
            />
          </el-select>
        </div>
        
        <div class="filter-item">
          <label>类型筛选：</label>
          <el-select 
            v-model="typeFilter" 
            placeholder="选择类型" 
            clearable
            style="width: 150px;"
            @change="fetchLogs"
          >
            <el-option label="全部" value="" />
            <el-option label="发布" value="publish" />
            <el-option label="订阅" value="subscribe" />
          </el-select>
        </div>
        
        <div class="filter-actions">
          <el-button size="small" @click="clearFilters">清空筛选</el-button>
        </div>
      </div>
    </div>
    <el-table :data="data">
      <el-table-column label="时间" width="180">
        <template #default="{ row }">
          {{ formatChineseTime(row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="120" />
      <el-table-column prop="topic" label="主题" width="240" />
      <el-table-column prop="message" label="消息" />
      
      <el-table-column prop="qos" label="QoS" width="80" />
      <el-table-column prop="retained" label="保留" width="80" />
    </el-table>
  </el-card>
</template>

<style scoped>
.filter-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.filter-actions {
  margin-left: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-item {
    justify-content: space-between;
  }
  
  .filter-actions {
    margin-left: 0;
    margin-top: 8px;
  }
}

/* 样式定义 */
.el-card {
  margin-bottom: 16px;
}

.el-table {
  width: 100%;
}
</style>